package com.cxmx.escort.common.alioss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UploadOss {

    private static String accessKeyId = "LTAI4FfX5bZ88t6rz7f2Ht9N";
    private static String accessKeySecret = "9gqid19opkRLSEmWLi9tP45XTAB5mx";
    private static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com/";
    private static String bucketName = "yingsite";
    /**
     * 阿里云图片地址
     **/
    public final static String GET_ALI_BUCK_URL = "https://yingsite.oss-cn-shenzhen.aliyuncs.com";
    public static String fileName = "yingsite/";//文件夹名称

    /**
     * 上传文件，返回访问链接
     * <p>Description: </p>
     *
     * @param imageFile
     * @return
     * @author: luoshun
     * @version: v1.0 2016年10月24日
     */
    public static String uploadFile(MultipartFile imageFile) {
        String fileName = imageFile.getOriginalFilename();
        try {
            InputStream stream = imageFile.getInputStream();
            Long size = imageFile.getSize();
            fileName = UploadOss.uploadFile(fileName, stream, size);
            return GET_ALI_BUCK_URL + fileName + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 【上传到阿里云】(这里用一句话描述这个方法的作用)
     *
     * @param key
     * @param stream
     * @param size
     * @return
     * @throws Exception
     */
    public static String uploadFile(String key, InputStream stream, long size) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String d = formatter.format(new Date());
        String first = d.substring(0, 7).replace("-", "");
        String sec = d.substring(8, 10);
        key = first + "/" + sec + "/" + key;
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(size);
        client.putObject(bucketName, fileName + key, stream, meta);
        return key;
    }

    /**
     * 【上传到阿里】(这里用一句话描述这个方法的作用)
     *
     * @param bucketName
     * @param key
     * @param filePath
     * @throws Exception
     */
    public static void uploadFile(String bucketName, String key, String filePath) throws Exception {
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        File file = new File(filePath);
        InputStream stream = new FileInputStream(file);

        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.length());
        //PutObjectResult result =
        client.putObject(bucketName, key, stream, meta);

    }


}
